package com.zzmemg.test_flutter

import android.app.Activity
import android.util.Log
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.EventChannel
import java.util.*
import kotlin.concurrent.timerTask

class NoticeChannel(var activity: Activity, flutterEngine: BinaryMessenger) : EventChannel.StreamHandler {

    companion object {
        private const val TAG = "NoticeChannel"
        private const val NOTICE_CHANNEL_NAME = "cn.xqw/notice"
    }

    private var channel: EventChannel
    private var index = 0
    private var eventSink: EventChannel.EventSink? = null

    init {
        channel = EventChannel(flutterEngine, NOTICE_CHANNEL_NAME)
        channel.setStreamHandler(this)
        startTime()
    }

    private fun startTime() {
        Timer().schedule(timerTask {
            index++
            val map = mapOf("name" to "success:$index", "age" to "$index")
            activity.runOnUiThread {
                Log.i(TAG, "==== get android result: $map")
                eventSink?.success(map)
            }
        }, 0, 1000)
    }

    override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
        Log.i(TAG, "====onListen: ${arguments.toString()}")
        eventSink = events
    }

    override fun onCancel(arguments: Any?) {
        Log.i(TAG, "====onCancel: ${arguments.toString()}")
        eventSink = null
        channel.setStreamHandler(null)
    }


}